package com.adtech.adms.system.web.action;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.adtech.adms.SessionKey;
import com.adtech.adms.commons.ErrorCode;
import com.adtech.adms.commons.tree.DataTypeTreeNode;
import com.adtech.adms.commons.tree.TreeNode;
import com.adtech.adms.commons.web.action.DataGridAction;
import com.adtech.adms.system.datadictionary.DataDictionaryConstants;
import com.adtech.adms.system.datadictionary.DataDictionaryHelper;
import com.adtech.adms.system.datadictionary.DataItem;
import com.adtech.adms.system.datadictionary.DataType;
import com.adtech.adms.system.service.DataDictionaryService;
import com.adtech.core.dao.query.FilterItem;
import com.adtech.core.dao.query.FilterMap;
import com.adtech.core.dao.query.Pager;
import com.adtech.core.dao.query.Sort;
import com.adtech.core.exception.ServiceException;
import com.adtech.core.exception.SystemException;
import com.adtech.core.util.StringUtil;
import com.adtech.core.util.TemplateUtil;
import com.adtech.core.web.action.AjaxResult;

import freemarker.template.TemplateException;

/**
 * 数据字典action
 * 数据字典的统一处理
 * @author Dormin 
 * @since 2011-6-13 
 * 
 * @Copyright (C) AD Tech Workshop All Right Reserved
 */
public class DataDictionaryAction extends DataGridAction {

	/**
	 * @function
	 * @param
	 * 
	 * @return
	 * @exception
	 * 
	 * @author
	 * @history
	 * 
	 */
	private static final long serialVersionUID = -6154039823083358616L;

	private static final Logger log = Logger.getLogger(DataDictionaryAction.class);

	private DataDictionaryService dataDictionaryService;
	private List<DataType> dataTypeList;
	private Integer dataTypeId;
	private String columns;
	private String form;
	private String id;
	private Object item;
	private Map<String, Object> valueMap;
	private Map<String, Object> queryMap = new HashMap<String, Object>();
	private DataType dataType;
	private List<TreeNode<DataType>> nodes;

	public void setDataDictionaryService(DataDictionaryService dataDictionaryService) {
		this.dataDictionaryService = dataDictionaryService;
	}

	public List<DataType> getDataTypeList() {
		return dataTypeList;
	}

	public void setDataTypeList(List<DataType> dataTypeList) {
		this.dataTypeList = dataTypeList;
	}

	public Integer getDataTypeId() {
		return dataTypeId;
	}

	public void setDataTypeId(Integer dataTypeId) {
		this.dataTypeId = dataTypeId;
	}

	public String getColumns() {
		return columns;
	}

	public void setColumns(String columns) {
		this.columns = columns;
	}

	public String getForm() {
		return form;
	}

	public void setForm(String form) {
		this.form = form;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public Object getItem() {
		return item;
	}

	public void setItem(Object item) {
		this.item = item;
	}

	public Map<String, Object> getQueryMap() {
		return queryMap;
	}

	public void setQueryMap(Map<String, Object> queryMap) {
		this.queryMap = queryMap;
	}

	public DataType getDataType() {
		return dataType;
	}

	public void setDataType(DataType dataType) {
		this.dataType = dataType;
	}

	public Map<String, Object> getValueMap() {
		return valueMap;
	}

	public void setValueMap(Map<String, Object> valueMap) {
		this.valueMap = valueMap;
	}

	public List<TreeNode<DataType>> getNodes() {
		return nodes;
	}

	public void setNodes(List<TreeNode<DataType>> nodes) {
		this.nodes = nodes;
	}

	/**
	 * 
	 * @function 进入数据字典管理页面
	 * @param
	 * 
	 * @return
	 * @exception
	 * 
	 * @author
	 * @history
	 * 
	 */
	public String main() {
		dataTypeList = DataDictionaryHelper.getDataTypeList().getTypeList();
		return SUCCESS;
	}
	
	public String getDataTypeTree() {
		dataTypeList = DataDictionaryHelper.getDataTypeList().getTypeList();
		nodes = new ArrayList<TreeNode<DataType>>();
		for(DataType dataType : dataTypeList) {
			DataTypeTreeNode treeNode = new DataTypeTreeNode(dataType);
			nodes.add(treeNode);
		}
		return SUCCESS;
	}

	/**
	 * 
	 * @function 根据选中的数据分类展示右侧列表
	 * @param
	 * 
	 * @return
	 * @throws IOException
	 * @throws TemplateException
	 * @throws URISyntaxException
	 * @exception
	 * 
	 * @author Dormin
	 * @history
	 * 
	 */
	public String right() throws TemplateException, IOException, URISyntaxException {
		if (dataTypeId != null) {
			dataType = DataDictionaryHelper.getDataTypeById(dataTypeId);
			DataType oldDataType = (DataType) session.get(SessionKey.DATA_TYPE);
			if (oldDataType != null && dataType.getId() != oldDataType.getId()) {
				session.put(SessionKey.QUERY_STATUS, null);
				this.setPager(new Pager());
				this.setSorter(new Sort());
				this.setFilterMap(new FilterMap());
			}
		} else {
			dataType = (DataType) session.get(SessionKey.DATA_TYPE);
			if (dataType == null) {
				dataType = DataDictionaryHelper.getDataTypeById(DataDictionaryConstants.DEFAULT_DATA_TYPE_ID);
			}
		}
		if (dataType == null) {
			log.error("data type " + dataTypeId + " doesn't exist.");
			return ERROR;
		}
		generateQueryMap(dataType);
		Map<String, List<DataItem>> rootMap = new HashMap<String, List<DataItem>>();
		rootMap.put(DataDictionaryConstants.DATA_DICTIONARY_TEMPLATE_PARAMS, dataType.getItems());
		String path = DataDictionaryConstants.DATA_DICTIONARY_TEMPLATE_COLUMNS;
		columns = TemplateUtil.process(path, rootMap,true);
		session.put(SessionKey.DATA_TYPE, dataType);
		return SUCCESS;
	}

	/**
	 * 
	 * @function 根据配置组装查询字段
	 * @param dataType
	 *            数据分类
	 * 
	 * @return
	 * @exception
	 * 
	 * @author Dormin
	 * @history
	 * 
	 */
	private void generateQueryMap(DataType dataType) {
		if (!StringUtil.isEmpty(dataType.getQuery())) {
			String[] queries = dataType.getQuery().split(",");
			for (String query : queries) {
				Object value = null;
				if (this.getFilterMap() != null) {
					FilterItem item = this.getFilterMap().get(query);
					if (item != null) {
						value = item.getFilterValue();
					}
				}
				queryMap.put(query, value);
			}
		}
	}

	@Override
	protected List<?> getModelDataGridList(Pager pager, FilterMap filtermap, Sort sort) throws SystemException {
		DataType dataType = (DataType) session.get(SessionKey.DATA_TYPE);
		if ((sort == null || sort.isEmpty()) && dataType.getSort()!=null) {
			sort = new Sort(dataType.getSort(), dataType.getOrder());
		}
		List<?> list = dataDictionaryService.getDataList(pager, filtermap.toExpression(), sort, dataType);
		sort.clear();
		return list;
	}

	/**
	 * 
	 * @function 删除(支持批量删除)
	 * @param
	 * 
	 * @return
	 * @throws SystemException
	 * @exception
	 * 
	 * @author Dormin
	 * @history
	 * 
	 */
	public String delete() throws SystemException {
		DataType dataType = (DataType) session.get(SessionKey.DATA_TYPE);
		if (dataType != null) {
			dataDictionaryService.delete(dataType, id);
			setAjaxResult(AjaxResult.success());
		} else {
			setAjaxResult(AjaxResult.failed(ErrorCode.DELETE_DATA_DIC_ERROR));
		}
		return SUCCESS;
	}

	/**
	 * 
	 * @function 新增
	 * @param
	 * 
	 * @return
	 * @throws IOException
	 * @throws TemplateException
	 * @throws URISyntaxException
	 * @exception
	 * 
	 * @author Dormin
	 * @history
	 * 
	 */
	public String add() throws TemplateException, IOException, URISyntaxException {
		DataType dataType = (DataType) session.get(SessionKey.DATA_TYPE);
		if (dataType != null) {
			Map<String, List<DataItem>> rootMap = new HashMap<String, List<DataItem>>();
			rootMap.put(DataDictionaryConstants.DATA_DICTIONARY_TEMPLATE_PARAMS, dataType.getItems());
			String path = DataDictionaryConstants.DATA_DICTIONARY_TEMPLATE_FORM;
			form = TemplateUtil.process(path, rootMap,true);
			ServletActionContext.getRequest().setAttribute("form", form);
		}
		return SUCCESS;
	}

	/**
	 * 
	 * @function 编辑
	 * @param
	 * 
	 * @return
	 * @throws IOException
	 * @throws TemplateException
	 * @throws URISyntaxException
	 * @throws SystemException 
	 * @exception
	 * 
	 * @author Dormin
	 * @history
	 * 
	 */
	public String edit() throws TemplateException, IOException, URISyntaxException, SystemException {
		DataType dataType = (DataType) session.get(SessionKey.DATA_TYPE);
		if (dataType != null) {
			item = dataDictionaryService.getByTypeAndId(dataType, Long.parseLong(id));
			Map<String, List<DataItem>> rootMap = new HashMap<String, List<DataItem>>();
			rootMap.put(DataDictionaryConstants.DATA_DICTIONARY_TEMPLATE_PARAMS, DataDictionaryHelper.setDataItemValue(item, dataType));
			String path = DataDictionaryConstants.DATA_DICTIONARY_TEMPLATE_FORM;
			form = TemplateUtil.process(path, rootMap,true);
			ServletActionContext.getRequest().setAttribute("form", form);
		}
		return SUCCESS;
	}
	
	public String enable() throws TemplateException, IOException, URISyntaxException, SystemException {
		DataType dataType = (DataType) session.get(SessionKey.DATA_TYPE);
		if (dataType != null) {
			dataDictionaryService.enable(dataType, Long.parseLong(id));
			
			setAjaxResult(AjaxResult.success());
		}
		return SUCCESS;
	}
	
	public String disable() throws TemplateException, IOException, URISyntaxException, SystemException {
		DataType dataType = (DataType) session.get(SessionKey.DATA_TYPE);
		if (dataType != null) {
			dataDictionaryService.disable(dataType, Long.parseLong(id));
			
			setAjaxResult(AjaxResult.success());
		}
		return SUCCESS;
	}

	/**
	 * 
	 * @function 保存
	 * @param
	 * 
	 * @return
	 * @throws SystemException 
	 * @throws ServiceException 
	 * @exception
	 * 
	 * @author Dormin
	 * @history
	 * 
	 */
	public String save() throws ServiceException, SystemException {
		DataType dataType = (DataType) session.get(SessionKey.DATA_TYPE);
		if (dataType != null) {
			dataDictionaryService.save(dataType, valueMap);
		}
		setAjaxResult(AjaxResult.success());
		return SUCCESS;
	}

//	/**
//	 * @function 构造电厂类型下拉列表
//	 * @param
//	 * @return String
//	 * 
//	 * @author Dormin
//	 * @throws SystemException
//	 */
//	public String fetchPowerType() throws SystemException {
//		List<Object> prowerTypeList = fetchFromDictionary(DataDictionaryConstants.POWER_TYPE);
//		List<String> results = new ArrayList<String>();
//		for (int i = 0; i < prowerTypeList.size(); i++) {
//			PowerType powerType = (PowerType) prowerTypeList.get(i);
//			// 构造下拉列表选项
//			results.add(powerType.getName());
//		}
//
//		setAjaxResult(AjaxResult.success(results));
//		return SUCCESS;
//	}
//
//	/**
//	 * @function 构造电厂性质下拉列表
//	 * @param
//	 * @return String
//	 * 
//	 * @author Dormin
//	 * @throws SystemException
//	 */
//	public String fetchPowerNature() throws SystemException {
//		List<Object> prowerNatureList = fetchFromDictionary(DataDictionaryConstants.POWER_NATURE);
//		List<String> results = new ArrayList<String>();
//		for (int i = 0; i < prowerNatureList.size(); i++) {
//			PowerNature powerNature = (PowerNature) prowerNatureList.get(i);
//			// 构造下拉列表选项
//			results.add(powerNature.getName());
//		}
//
//		setAjaxResult(AjaxResult.success(results));
//		return SUCCESS;
//	}
//
//	/**
//	 * @function 构造投资主体下拉列表
//	 * @param
//	 * @return String
//	 * 
//	 * @author Dormin
//	 * @throws SystemException
//	 */
//	public String fetchInvestor() throws SystemException {
//		List<Object> investorsList = fetchFromDictionary(DataDictionaryConstants.INVESTORS_ID);
//		List<String> results = new ArrayList<String>();
//		for (int i = 0; i < investorsList.size(); i++) {
//			Investor investors = (Investor) investorsList.get(i);
//			// 构造下拉列表选项
//			results.add(investors.getName());
//		}
//
//		setAjaxResult(AjaxResult.success(results));
//		return SUCCESS;
//	}
//
//	/**
//	 * @function 构造电压等级下拉列表
//	 * @param
//	 * @return String
//	 * 
//	 * @author Dormin
//	 * @throws SystemException
//	 */
//	public String fetchVoltage() throws SystemException {
//		List<Object> volList = fetchFromDictionary(DataDictionaryConstants.VOL_CLASS_ID);
//		List<String> results = new ArrayList<String>();
//		for (int i = 0; i < volList.size(); i++) {
//			VolClass vol = (VolClass) volList.get(i);
//			// 构造下拉列表选项
//			results.add(vol.getVolClassType());
//		}
//
//		setAjaxResult(AjaxResult.success(results));
//		return SUCCESS;
//
//	}
//
//	/**
//	 * @function 根据typeId取得数据字典中的数据
//	 * @param
//	 * @return List<Object>
//	 * 
//	 * @author Dormin
//	 * @throws SystemException
//	 */
//	private List<Object> fetchFromDictionary(int typeId) throws SystemException {
//		return dataDictionaryService.getValueList(typeId);
//	}
}
